#include <FreeRTOS.h>
#include <task.h>
#include <completion.h>
#include <mutex.h>
#include <string.h>
#include <mailbox.h>
#include <interrupt.h>
#include <msleep.h>
#include <kmalloc.h>
#include <gpio.h>
#include <i2c.h>
#include <pwm.h>

struct mutex mutex;
struct completion done;

int i2c_adapter = 0;

void i2c_write_callback(void *data)
{
	printk("%s\n",data);
	complete_isr(&done);
}

void i2c_test_write(uint16_t cmd, uint16_t value)
{
	struct i2c_msg w_msg;
	uint8_t buf[16] = {0, 0};

	buf[0] = cmd;
	buf[1] = value;

	printk("write reg = 0x%x, data = 0x%x\n", buf[0], buf[1]);
	w_msg.adapter = i2c_adapter;
	w_msg.addr = 0x37;
	w_msg.flags = I2C_PIO_MODE;
	w_msg.buf_data_format = REG_8BIT_VALUE_8BIT;
	w_msg.len = 1;
	w_msg.buf = buf;
	w_msg.callback = NULL;
	w_msg.cb_data = NULL;

	i2c_write(&w_msg);

}

int i2c_test_read(uint32_t cmd)
{
	struct i2c_msg r_msg;
	uint8_t buf[2] = {0, 0};

	buf[0] = cmd;

	r_msg.adapter = i2c_adapter;
	r_msg.addr = 0x37;
	r_msg.flags = I2C_PIO_MODE;
	r_msg.buf_data_format = REG_8BIT_VALUE_8BIT;
	r_msg.len = 1;
	r_msg.buf = buf;

	i2c_read(&r_msg);
	printk(" read data = 0x%x\n", buf[1]);

	return buf[1];
}

static void task_1(void *arg)
{
	int count = 0;

	while (1) {
		mutex_lock(&mutex);
		printk("hello world %s, %d\n", __func__, __LINE__);
		mutex_unlock(&mutex);

		i2c_test_write(0x10 ,0x1);
		msleep(1000);
	}
}


void vApplicationMallocFailedHook(void)
{
	printk("failed allocate\n");

}

int main(void)
{
	printk("hello world %s, %d\n", __func__, __LINE__);

	struct i2c_config config;
	uint32_t buf_size;
	uint32_t buf_addr;


	memset(&config, 0x0, sizeof(config));

	/* gpio_set_func(GPIO_PORT_A, GPIO_FUNC_3, 0x1<<17); */
	/* struct pwm_config pwm; */
	/* pwm.period_ns = 1000000; */
	/* pwm.duty_ns = 50000; */
	/* pwm.init_level = PWM_INIT_HIGH; */
	/* pwm_channel_config(0, &pwm); */
	/* pwm_channel_enable(0); */

	gpio_set_func(GPIO_PORT_B, GPIO_FUNC_0, 0x3<<25);
	buf_size = 4 * 1024;
	buf_addr = (uint32_t)kmalloc(buf_size);
	if(!buf_addr)
		printk("%s %d, rw_buf_addr alloc failed\n",__func__,__LINE__);

	config.adapter = i2c_adapter;
	config.dma_buf_size = buf_size;
	config.dma_buf_addr = buf_addr;
	i2c_init(&config);

	mutex_init(&mutex);
	init_completion(&done);

	xTaskCreate((TaskFunction_t)task_1,    /* 任务入口函数 */
			(const char *)"task_1",   /* 任务名字 */
			(uint16_t)512,         /* 任务栈大小 */
			(void *)NULL,         /* 任务入口函数参数 */
			(UBaseType_t)1,     /* 任务的优先级 */
			(TaskHandle_t *)NULL); /* 任务控制块指针 */

	vTaskStartScheduler();   /* 启动任务，开启调度 */

	return 0;
}
